package mark.tom.pistols.encryptor.ciphers;

import mark.tom.pistols.algorithm.encryption.Base64Encryption;
import mark.tom.pistols.algorithm.encryption.RSAEncryption;
import mark.tom.pistols.encryptor.DataEncrypt;

/**
 * @Description: RSA算法进行数据加密的方法
 * @Author: ttmk110@163.com
 * @Package: mark.tom.pistols.encryptor
 * @Date: 2020/7/11
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date: </ModifyLog>
 */
public class RSADataEncrypt extends DataEncrypt {

    private final static int RSA_CONTENT_MAX_LENGTH = 117;

    @Override
    public String getEncryptData(String input) throws Exception {
        StringBuilder sb = new StringBuilder();
        int times = input.length() / RSA_CONTENT_MAX_LENGTH;
        if (input.length() % RSA_CONTENT_MAX_LENGTH != 0) {
            times++;
        }
        for (int i = 0; i < times; i++) {
            int startIndex = RSA_CONTENT_MAX_LENGTH * i;
            int endIndex = RSA_CONTENT_MAX_LENGTH * (i + 1) > input.length() ? input.length() : RSA_CONTENT_MAX_LENGTH * (i + 1);
            String subStr = input.substring(startIndex, endIndex);
            sb.append(getEncryptStr(subStr, pubKey));
        }
        return sb.toString();
    }

    private String getEncryptStr(String input, String pubKey) throws Exception {
        return new String(Base64Encryption.encrypt(RSAEncryption.encrypt(pubKey, input.getBytes(UTF_8))), UTF_8);
    }

}
